package com.github.cyf.cookie;

import com.github.cyf.common.module.Rs;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author chenyifan
 * @create 2024-09-24 11:24
 */
@RestController
@RequestMapping("/cookie")
@Api(tags = "cookie 测试")
public class CookieController {

    @Autowired
    private HttpServletResponse response;

    @GetMapping("/setCookie")
    @ApiOperation("设置cookie")
    @ApiOperationSupport(order = 1)
    public Rs setCookie() {
        Cookie cookie1 = new Cookie("k1", UUID.randomUUID().toString());
        Cookie cookie2 = new Cookie("k2", UUID.randomUUID().toString());
        response.addCookie(cookie1);
        response.addCookie(cookie2);
        return Rs.ok("设置cookie成功");
    }

    @GetMapping("/getCookie")
    @ApiOperation("获取cookie")
    @ApiOperationSupport(order = 2)
    public Rs getCookie(@CookieValue("k1") String v1, @CookieValue("k2") String v2) {
        return Rs.ok().set("k1", v1).set("k2", v2);
    }

    @GetMapping("/setSession")
    @ApiOperation("设置 session")
    @ApiOperationSupport(order = 3)
    public Rs setSession(HttpSession session) {
        session.setAttribute("s1", UUID.randomUUID().toString());
        session.setAttribute("s2", UUID.randomUUID().toString());
        int maxInactiveInterval = session.getMaxInactiveInterval();
        return Rs.ok("设置session成功, 有效期：" + maxInactiveInterval + "s");
    }

    @GetMapping("/getSession")
    @ApiOperation("获取 session")
    @ApiOperationSupport(order = 4)
    public Rs getSession(HttpSession session) {
        return Rs.ok().set("s1", session.getAttribute("s1"))
                .set("s2", session.getAttribute("s2"));
    }
}
